****************************************************************
* CALIBRATION SPAIN            *
****************************************************************

*** 1) Endowment of Tradables

** COMPUTE THE ENDOWMENT PROCESS FOR TRADABLES

use "C:\Users\g1fia01\Desktop\Research\JMP\JMP Replication Package\DATA\Stata\input\tradable_data.dta",clear
gen tradables=tradable
gen timevar=_n

gen ltra=log(tradables/total) 
tsset timevar
reg ltra timevar
predict htra, residual
predict ttra, xb

arima htra  ,arima(1,0,0) noconstant 
matrix list e(b) // This list the variables of the Rho
matrix  rho=1000000000000000*e(b) // This list the variables of the V
matrix list rho ,format(%128.0f)

*** 2) SHOCKS TO PRIVATE SPREADS
 use "C:\Users\g1fia01\Desktop\Research\JMP\JMP Replication Package\DATA\Stata\input\nonperforming.dta",clear
 
tsset year
gen nonperf0=log(nonperf)

/* Linear DETRENDED*/
gen timevar=_n
reg nonperf0 timevar
predict htra, residual
gen ehtra=exp(htra)

arima nonperf0 ,arima(1,0,0) 


**3) COMPUTE TARGETS FOR CALIBRATION

use "C:\Users\g1fia01\Desktop\Research\JMP\JMP Replication Package\DATA\Stata\input\annual_panel.dta",clear
gen timevar=_n
gen ltra=pv_debt
keep if timevar<=14
tsset timevar
reg ltra timevar
predict htra, residual
predict ttra, xb
rename htra pv_debt_cycle


reg pub_debt timevar
predict htra, residual
rename htra pub_debt_cycle

reg total timevar
predict htra, residual
rename htra total_debt_cycle

reg spread timevar
predict htra, residual
rename htra spread_debt_cycle

*keep time pv_debt pub_debt total spread pv_debt_cycle pub_debt_cycle total_debt_cycle spread_debt_cycle
keep time pv_debt_cycle pub_debt_cycle total_debt_cycle spread_debt_cycle
save "C:\Users\g1fia01\Desktop\Research\JMP\JMP Replication Package\DATA\Stata\output\targets.dta",replace

**3) COMPUTE TRANSITION PATHS FOR VALIDATION
use "C:\Users\g1fia01\Desktop\Research\JMP\JMP Replication Package\DATA\Stata\input\tradable_data.dta",clear
gen tradables=tradable
gen timevar=_n

gen ltra=log(tradables/total) 
tsset timevar
reg ltra timevar
predict htra, residual

rename htra output
rename year time
keep time output
merge 1:1 time using "C:\Users\g1fia01\Desktop\Research\JMP\JMP Replication Package\DATA\Stata\input\annual_panel.dta"
drop _merge
rename time year
merge 1:1 year using "C:\Users\g1fia01\Desktop\Research\JMP\JMP Replication Package\DATA\Stata\input\nonperforming.dta"

rename pv_debt pv_iip
rename pub_debt pub_iip
drop total gdp _merge
keep if year>=1999
keep if year<=2017
drop year
order output pv_iip nonperf pub_iip spread

save "C:\Users\g1fia01\Desktop\Research\JMP\JMP Replication Package\DATA\Stata\output\Output_PViip_NonPerf_9917.dta", replace

